package com.fhd.servlet;

import com.fhd.constant.Constants;
import com.fhd.pojo.Client;
import com.fhd.pojo.Manager;
import com.fhd.pojo.Merchant;
import com.fhd.service.Client.ClientService;
import com.fhd.service.Client.ClientServiceImplement;
import com.fhd.service.Manager.ManagerService;
import com.fhd.service.Manager.ManagerServiceImplement;
import com.fhd.service.Merchant.MerchantService;
import com.fhd.service.Merchant.MerchantServiceImplement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        String roleId = req.getParameter("roleId");
        Client client = null;
        Merchant merchant = null;
        Manager manager = null;

        // 控制层调用业务层
        switch (roleId) {
            case "1":   // 客户
                ClientService clientService = new ClientServiceImplement();
                client = clientService.login(userCode,userPassword);
                if (client != null) {
                    // 找得到客户，并且密码正确,把客户放到session中,进到客户端
                    req.getSession().setAttribute(Constants.CLIENT_SESSION,client);
                    resp.sendRedirect("jsp/clientFrame.jsp");
                }
                break;
            case "2":   // 商户
                MerchantService merchantService = new MerchantServiceImplement();
                merchant = merchantService.login(userCode,userPassword);
                if (merchant != null) {
                    // 找得到商户，并且密码正确,把商户放到session中,进到商户端
                    req.getSession().setAttribute(Constants.MERCHANT_SESSION,merchant);
                    resp.sendRedirect("jsp/merchantFrame.jsp");
                }
                break;
            case "3":   // 管理端
                ManagerService managerService = new ManagerServiceImplement();
                manager = managerService.login(userCode,userPassword);
                if (manager != null) {
                    // 找得到管理端，并且密码正确,把管理端放到session中,进到管理端
                    req.getSession().setAttribute(Constants.MANAGER_SESSION,manager);
                    resp.sendRedirect("jsp/managerFrame.jsp");
                }
                break;
        }

        if (client == null && merchant == null && manager == null) {
            // 找不到人，返回登录页，并携带错误信息
            req.getSession().setAttribute("loginMessage","账号或密码错误");
            resp.sendRedirect("login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
